
<template>
  <div class="app-container action-active-container">
    <div class="back-content flex-between">
      <div class="back-main flex-normal">
        <span class="back-icon el-icon-back" @click="$router.go(-1)"></span>
        <span class="back-label">编辑活动</span>
      </div>
    </div>
    <div class="action-active-main flex-normal">
      <div class="active-config-content">
        <div class="app-dialog active-config-main">
          <!-- <vue-scroll> -->
          <el-form
            class="form-content"
            ref="active-form" label-position="left"
            :model="currentItem" v-loading="boo.loading"
            label-width="120px">
            <div class="form-title flex-between">
              <span class="title-txt">活动信息</span>
              <el-button :loading="boo.isPrice" type="primary" size="small" @click="submit">发布活动</el-button>
            </div>
            <el-form-item class="form-content-item" label="活动类型">
              <el-select v-model="currentItem.activityTypeId" placeholder="请选择" disabled>
                <el-option v-for="(option, index) in getDictItem('activityType')" :key="index" 
                :label="option.dictLabel" :value="option.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="activeFiles.activityName"
            class="form-content-item" label="活动名称">
              <el-input :disabled="$route.query['id'] ? true : false" v-model="currentItem.activityName" placeholder="洗车活动优惠"></el-input>
            </el-form-item>
            <el-form-item v-if="activeFiles.acceptingUnit" class="form-content-item" label="接收单位">
              <el-input v-model="currentItem.acceptingUnit" placeholder="太平洋保险"></el-input>
            </el-form-item>
            <el-form-item v-if="activeFiles.serveTypeIds" label="服务内容">
              <div class="package-model-container ">
                <div class="select-content">
                  <el-table :data="tableData" height="180"
                    style="width: 100%;">
                    <el-table-column prop="serveTypeId" label="服务类型">
                      <template slot-scope="{row}">
                        {{ resetGlfwType(dictTypeList, row.serveTypeId) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="serveName" label="服务名称"></el-table-column>
                    <el-table-column prop="serveDetails" label="服务内容"></el-table-column>
                    <el-table-column prop="itemNum" label="服务次数">
                      <template slot-scope="{row}">
                        <div>{{ row.itemNum || '0' }}</div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-if="shopType == 4"
                      label="用户优惠价"
                      align="center"
                      prop="discountedPrice">
                      <template slot-scope="{row}"> 
                        {{ row.discountedPrice || '0.00' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="price" label="市场单价"></el-table-column>
                    <el-table-column prop="writeOffFee" label="核销单价"></el-table-column>
                    <el-table-column v-if="currentItem.activityTypeId == 7" prop="probability" label="中奖概率">
                      <template slot-scope="{row}">
                        <el-input-number v-model="row.probability"
                        controls-position="right" :precision="2" :step="0.1"
                        :min="0" :max="1"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column prop="total" label="总计"></el-table-column>
                  </el-table>
                  <div class="sums-content flex-column">
                    <div class="sums-item flex-normal">
                      <span class="sums-label">优惠总计</span>
                      <span class="sums-val error">{{sumsObj.preferentialPrice}}</span>
                    </div>
                    <div class="sums-item flex-normal">
                      <span class="sums-label">核销总计</span>
                      <span class="sums-val">{{sumsObj.writeOffPrice}}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>

            <el-form-item v-if="activeFiles.number" class="form-content-item" label="活动份数">
              <div class="num-form-content flex-normal">
                <el-input disabled class="num-form" v-model="currentItem.number" placeholder="输入数量"></el-input>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.activityTime" class="form-content-item" label="活动时间">
              <div class="time-date-select-container flex-normal">
                <div class="form-content-row flex-normal">
                  <div class="item-col">
                    <el-date-picker
                      v-model="currentItem.startingTime"
                      type="date" value-format="yyyy-MM-dd"
                      placeholder="选择开始日期">
                    </el-date-picker>
                  </div>
                  <div class="item-col">
                    <span class="col-txt">至</span>
                  </div>
                  <div class="item-col">
                    <el-date-picker
                      v-model="currentItem.endTime"
                      type="date" value-format="yyyy-MM-dd"
                      placeholder="选择结束日期">
                    </el-date-picker>
                  </div>
                </div>
              </div>
            </el-form-item>

            <el-form-item v-if="activeFiles.periodOfValidity" class="form-content-item" label="卡券有效期">
              <div class="form-content-row flex-normal">
                <template v-if="currentItem.whetherToClosingDate">
                  长期有效
                </template>
                <template v-else>
                  {{currentItem.closingDate}}
                </template>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.purchaseRestrictions && currentItem.activityTypeId != 7" class="form-content-item" 
              label="购买限制">
              <div class="form-content-row flex-normal">
                <template v-if="currentItem.limitation">
                  每用户仅可购买 {{ currentItem.emptionRestrict }} 份
                </template>
                <template v-else>
                  无限制
                </template>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.purchaseRestrictions && currentItem.activityTypeId == 7" class="form-content-item" 
              label="抽奖限制">
              <div class="form-content-row flex-normal">
                每用户仅可抽奖 {{currentItem.emptionRestrict}} 次
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.sharedRedEnvelope" class="form-content-item" label="分享红包">
              <div class="form-content-row flex-normal">
                <div class="item-col">
                  <span class="col-label">奖励条件</span>
                </div>
                <div class="item-col">
                  <el-radio-group disabled v-model="currentItem.rewardCondition">
                    <el-radio :label="1">已购客户</el-radio>
                    <el-radio :label="0">所有客户</el-radio>
                  </el-radio-group>
                </div>
              </div>
              <div class="form-content-row flex-normal">
                <div class="item-col">
                  <el-checkbox disabled v-model="currentItem.whetherToShare"></el-checkbox>
                </div>
                <div class="item-col">
                  <span class="col-txt">分享成交后后，得</span>
                </div> 
                <div class="item-col">
                  <el-input disabled class="num-form" v-model="currentItem.completeIncome" placeholder="0.00"></el-input>
                </div>
                <div class="item-col">
                  <span class="col-txt">元</span>
                </div> 
                <div class="item-col">
                  <div class="warning-desc flex-normal">
                    <i class="desc-icon el-icon-info"></i>
                    <span class="desc-txt">该费用将从活动收益中扣除</span>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.activeOptions" class="form-content-item" label="激活选项">
              <div class="form-content-row flex-normal">
                <div class="item-col">
                  <span class="col-label">到店激活</span>
                </div>
                <div class="item-col">
                  <el-radio-group disabled v-model="currentItem.shopActivation">
                    <el-radio :label="0">是</el-radio>
                    <el-radio :label="1">否</el-radio>
                  </el-radio-group>
                </div>
              </div>
              <div class="form-content-row flex-normal">
                <div class="item-col">
                  <span class="col-label">激活截止日期</span>
                </div>
                <div class="item-col col-time">
                  <el-date-picker disabled
                    v-model="currentItem.activationClosingDate"
                    type="date"
                    placeholder="选择时间">
                  </el-date-picker>
                </div>
              </div>
              <div class="form-content-row flex-normal" v-if="currentItem.shopActivation != 1">
                <div class="item-col">
                  <span class="col-label">未激活券码</span>
                </div>
                <div class="item-col">
                  <el-radio-group v-model="currentItem.activationStatus">
                    <el-radio :label="1">到期未激活自动退款</el-radio>
                    <el-radio :label="2">到期未激活自动激活</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.whoWillBearTheCost" class="form-content-item" label="技术服务费">
              <div class="form-content-row flex-normal">
                <div class="item-col">
                  <el-radio-group disabled v-model="currentItem.skillServeFee">
                    <el-radio :label="0">商户承担</el-radio>
                    <el-radio :label="1">用户承担</el-radio>
                  </el-radio-group>
                </div>
                <div class="item-col">
                  <div class="warning-desc flex-normal">
                    <i class="desc-icon el-icon-info"></i>
                    <span class="desc-txt">该订单技术服务费为{{currentItem.serviceFee || '0.00'}}元</span>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.targetedUsers" label="定向用户">
              <div class="form-content-row">
                <div class="user-list-title flex-between">
                  <span class="title-label">用户列表({{(currentItem.acddUsers || []).length}})</span>
                  <div class="title-btn-content flex-normal">
                    <el-button type="primary" size="small" @click="exportUserTmp">下载模板</el-button>
                    <el-button type="primary" size="small" @click="importUser">导入</el-button>
                    <el-button type="primary" size="small" @click="addUser">添加用户</el-button>
                  </div>
                </div>
                <div class="user-list app-table-container">
                  <template v-if="currentItem.activityTypeId != 6">
                    <template v-if="currentItem.activityTypeId == 2">
                      <el-table width="100%" v-loading="boo.loading" :data="(currentItem.acddUsers || [])" height="300">
                        <el-table-column
                          label="开始时间"
                          align="center">
                          <template slot-scope="{row}">
                            <el-date-picker
                              :disabled="row.useStatus != 1 ? true: false"
                              v-model="row.orderTimeStart"
                              type="date"  size="small"
                              placeholder="选择日期">
                            </el-date-picker>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="购买有效期(天)"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input-number size="small"
                            :disabled="row.useStatus != 1 ? true: false"
                            v-model="row.payValidDay" 
                            controls-position="right"
                            :min="1"></el-input-number>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="手机号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.phone" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="姓名"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.name" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="车牌号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.licensePlate" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="卡券有效期"
                          align="center">
                          <template slot-scope="{row}">
                            <el-select :disabled="row.useStatus != 1 ? true: false" v-model="row.orderPeriodValidity" placeholder="请选择">
                              <el-option label="1个月" :value="1"></el-option>
                              <el-option label="3个月" :value="2"></el-option>
                              <el-option label="6个月" :value="3"></el-option>
                              <el-option label="1年" :value="4"></el-option>
                              <el-option label="2年" :value="5"></el-option>
                              <el-option label="3年" :value="6"></el-option>
                            </el-select>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="操作"
                          align="center" width="100"
                          class-name="small-padding fixed-width"
                        >
                          <template slot-scope="{row, $index}">
                            <el-button
                              size="mini" :disabled="row.useStatus != 1 ? true: false"
                              type="text" @click="removeTargetUser($index)"
                              icon="el-icon-del"
                              >移除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                    <template v-else-if="currentItem.activityTypeId == 5">
                      <el-table width="100%" v-loading="boo.loading" :data="(currentItem.acddUsers || [])" height="300">
                        <el-table-column
                          label="手机号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.phone" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="姓名"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.name" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="车牌号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.licensePlate" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="车架号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.vehicleIdentificationNumber" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="备注"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.commentContent" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="操作"
                          align="center" width="100"
                          class-name="small-padding fixed-width"
                        >
                          <template slot-scope="{row, $index}">
                            <el-button
                              size="mini" :disabled="row.useStatus != 1 ? true: false"
                              type="text" @click="removeTargetUser($index)"
                              icon="el-icon-del"
                              >移除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                    <template v-else>
                      <el-table width="100%" v-loading="boo.loading" :data="(currentItem.acddUsers || [])" height="300">
                        <el-table-column
                          label="手机号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.phone" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="姓名"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.name" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="车牌号"
                          align="center">
                          <template slot-scope="{row}">
                            <el-input :disabled="row.useStatus != 1 ? true: false" v-model="row.licensePlate" size="small"></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="操作"
                          align="center" width="100"
                          class-name="small-padding fixed-width"
                        >
                          <template slot-scope="{row, $index}">
                            <el-button
                              size="mini" :disabled="row.useStatus != 1 ? true: false"
                              type="text" @click="removeTargetUser($index)"
                              icon="el-icon-del"
                              >移除</el-button
                            >
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </template>
                  <template v-if="currentItem.activityTypeId == 6">
                    <el-table width="100%" v-loading="boo.loading" :data="(currentItem.acddUsers || [])" height="300">
                      <el-table-column
                        label="手机号"
                        align="center"
                        :show-overflow-tooltip="true">
                        <template slot-scope="{row}">
                          {{ row.phone || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="姓名"
                        align="center"
                        :show-overflow-tooltip="true">
                        <template slot-scope="{row}">
                          {{ row.name || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="红包金额"
                        align="center"
                        :show-overflow-tooltip="true">
                        <template slot-scope="{row}">
                          {{ row.balance || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="车牌号"
                        align="center"
                        :show-overflow-tooltip="true">
                        <template slot-scope="{row}">
                          {{ row.licensePlate || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="商业险保单号"
                        align="center"
                        :show-overflow-tooltip="true">
                        <template slot-scope="{row}">
                          {{ row.insureCode || '' }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </div>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.shopIds" label="适用商户">
              <template v-if="shopType == 4">
                <div class="form-content-row flex-normal">
                  <div class="item-col">
                    <el-checkbox-group v-model="currentItem.shopPool">
                      <el-checkbox v-for="(checkbox) in getDictItem('shopPool')" :key="checkbox.dictValue" 
                      :label="checkbox.dictValue">{{checkbox.dictLabel}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="form-content-row flex-normal">
                  <div class="item-col">
                    <el-checkbox-group disabled v-model="currentItem.shopPool">
                      <el-checkbox v-for="(checkbox) in getDictItem('shopPool')" :key="checkbox.dictValue" 
                      :label="checkbox.dictValue">{{checkbox.dictLabel}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
                <div class="form-content-row flex-normal">
                  <div class="storeList-model-container">
                    <div class="store-list-title-container flex-between">
                      <div class="title-content flex-center">
                        <span class="title-txt">商家列表（{{shopList.length}}家）</span>
                      </div>
                    </div>
                    <el-scrollbar class="store-list-main">
                      <div :class="['item flex-between', item.isChecked && 'active']"
                        v-for="item in shopList" :key="item.id">
                        <div class="item-content flex-normal">
                          <span class="item-label ellipsis-1">{{item.shopName}}</span>
                          <span class="item-desc ellipsis-1">{{item.shopAddress}}</span>
                        </div>
                        <div :class="['item-action flex-normal', item.isChecked && 'active']">
                          <span class="action-icon car-common-icon">&#xe663;</span>
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </div>
              </template>
            </el-form-item>
            <el-form-item v-if="activeFiles.clusteringConditions" class="form-content-item" label="成团条件">
              <div class="form-content-row flex-column">
                <el-radio disabled v-model="currentItem.clusteringCondition" :label="0">阶梯团购</el-radio>
                <div class="ct-list" v-if="currentItem.clusteringCondition == '0' && currentItem['acddGroupBuyings']">
                  <div class="ct-item flex-normal" v-for="(it, idx) in currentItem['acddGroupBuyings']" :key="idx">
                    <div class="item-col max-mix">
                      <el-input disabled v-model="it.miniValue" placeholder="输入数量"></el-input>
                    </div>
                    <div class="item-col">
                      <span class="col-txt">至</span>
                    </div>
                    <div class="item-col max-mix">
                      <el-input disabled v-model="it.maxValue" placeholder="输入数量"></el-input>
                    </div>
                    <div class="item-col">
                      <span class="col-txt">时，价格为</span>
                    </div>
                    <div class="item-col col-money">
                      <el-input disabled v-model="it.price" placeholder="输入金额">
                        <span class="col-txt" slot="suffix">元</span>
                      </el-input>
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-content-row flex-column">
                <el-radio disabled v-model="currentItem.clusteringCondition" :label="1">普通团购</el-radio>
                <div class="ct-list" v-if="currentItem.clusteringCondition == '1'">
                  <div class="ct-item flex-normal">
                    <div class="item-col">
                      <span class="col-txt">团购统一价</span>
                    </div>
                    <div class="item-col col-money">
                      <el-input disabled v-model="currentItem.groupBuyingPrice" placeholder="输入金额">
                        <span class="col-txt" slot="suffix">元</span>
                      </el-input>
                    </div>
                  </div>
                </div>            
              </div>
              <div class="form-content-row flex-normal">
                <div class="warning-desc flex-normal">
                  <i class="desc-icon el-icon-info"></i>
                  <span class="desc-txt">活动达到新的阶梯时，付款差价将在活动结束时返还至用户账户</span>
                </div>
              </div>
            </el-form-item>
            <el-form-item v-if="activeFiles.remarks" class="form-content-item" :label="currentItem.activityTypeId == 7 ? '活动规则' : '活动描述'">
              <el-input type="textarea" disabled :rows="3" 
              v-model="currentItem.remarks" 
              :placeholder="currentItem.activityTypeId == 7 ? '请设置活动规则' : '请输入活动描述'"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <import-dialog ref="importDialog" title="导入用户" url="/system/acddUser/importUser"
    @import-success="importSuccess"/>
  </div>
</template>

<script>
import {isPhoneNum} from '@/utils/tools.js'
import {
  editActivityDate, getActiveFiles, getActivityDetail
} from "@/api/activeManage/active";
import { mapGetters } from 'vuex';
import {
  getShopListByPool
} from "@/api/activeManage/active";

import {
  getServeTypeDict, buildOneselfServeList
} from "@/api/common/index";
import {
  exportOrientTemplate, exportRedPacketTemplate, exportGiveTemplate
} from "@/api/download";
export default {
  name: "storeActionActive",
  components: {
    "import-dialog": () => import("@/rhComponents/dialog/import-dialog.vue"),
  },
  computed: {
    ...mapGetters(['shopType']),
    tableData(){
      let { activityTypeId } = this.currentItem
      let item = {
        serveTypeId: '',
        id: '', 
        serveName: '谢谢惠顾',
        price: '0',
        writeOffFee: '0',
        itemNum: '0',
        discountedPrice: '0.00',
        probability: this.probability
      }
      this.serverList.forEach(item => {
        this.$set(item, 'total', this.computedRowTotal(item))
        this.$set(item, 'scTotal', this.computedRowScTotal(item))
      })
      this.computedSums(this.serverList)
      if(activityTypeId == 7){
        let idx = this.serverList.findIndex(i => i.id == '-1')
        if(idx == -1){
          this.serverList.push(item)
        }
      }
      return this.serverList
    },
  },
  data() {
    return {
      currentItem: {},
      activeFiles: {},
      serverList: [],
      dictTypeList: [],
      shopList: [],
      sumsObj: {},
      boo: {
        loading: false,
        isPrice: false
      },
      dictsList: [
        { label: "活动类型", name: "activityType", deptType: "activityType", child: [] },
        { label: "商户池", name: "shopPool", deptType: "shopPool", child: [] }
      ],
    };
  },
  async mounted(){
    let _self = this, {id, activeType} = this.$route.query
    _self.initGetDicts().then(async res => {
      await _self.getActiveDetail(id)
      let { activityTypeId } = _self.currentItem
      await _self.queryServeTypeDict()
      await getActiveFiles({activityTypeId}).then(res => {
        _self.activeFiles = res.data
      })
      await _self.getServeList()
      await _self.queryShopListByPool()
    })
  },
  methods: {
    getDictItem(name){
      let item = this.dictsList.find(i => i.deptType == name)
      let idx = item.child.findIndex(i => (i.dictLabel == '内部发行卡券') || (i.dictLabel == '内部发行卡卷'))
      if(idx != -1){
        item.child.splice(idx, 1)
      }
      return item.child || []
    },
    // 获取每一页中的题目
    toTreeData(list){
      let arrTree = []
      let arrObj = list.reduce((acc, cur) => {
        // 如果不存在这个键，则设置它赋值 [] 空数组
        if (!acc[cur.serveTypeTwo]) {
          acc[cur.serveTypeTwo] = [];
        }
        cur.value = cur.id
        cur.label = cur.serveType
        acc[cur.serveTypeTwo].push(cur)
        return acc
      }, {})
      for(let key in arrObj){
        arrTree.push({
          value: key,
          label: key == '0' ? '服务' : '外部卡券',
          children: arrObj[key]
        })
      }
      return arrTree
    },
    computedRowTotal(row){
      let total = parseFloat(row.writeOffFee)
      return total.toFixed(2)
    },
    computedRowScTotal(row){
      let total = parseFloat(row.price)
      return total.toFixed(2)
    },
    computedSums(list){
      let _self = this, obj = {marketPrice: '0.00', preferentialPrice: '0.00', writeOffPrice: '0.00'}
      list.forEach(item => {
        obj.writeOffPrice = parseFloat(obj.writeOffPrice) + parseFloat(item.total)
        obj.marketPrice = parseFloat(obj.marketPrice) + parseFloat(item.scTotal)
      })
      obj.preferentialPrice = parseFloat(obj.marketPrice) - parseFloat(obj.writeOffPrice)
      _self.sumsObj = {...obj}
    },
    resetGlfwType(list, id){
      let emitItem = {}, arr = []
      list.forEach(item => {
        item.children.forEach(i => {
          i.labelStr = `${item.label}-${i.label}`
        })
        arr = [...arr, ...item.children]
      })
      emitItem = arr.find(i =>i.id == id)
      if(emitItem) return emitItem.labelStr
      return '---'
    },
    async getActiveDetail(id){
      if(!id) return
      let isSuccess = false, _self = this
      await getActivityDetail(id).then(res => {
        let {
          shopPool, suitShopIds,
          serveTypeIds,
        } = res.data
        shopPool = shopPool ? shopPool.split(',') : []
        suitShopIds = suitShopIds ? suitShopIds.split(',') : []

        serveTypeIds = serveTypeIds ? serveTypeIds.split(',') : []
        _self.currentItem = res.data
        _self.currentItem.shopPool = shopPool
        _self.currentItem.suitShopIds = suitShopIds
        _self.currentItem.serveTypeIds = serveTypeIds
        isSuccess = true
      })
      return isSuccess
    },
    /** 查询服务类型列表 */
    async queryServeTypeDict() {
      let _self = this, isSuccess = false
      await getServeTypeDict()
      .then((res) => {
        isSuccess = true
        _self.dictTypeList = _self.toTreeData(res.data)
      })
      return isSuccess
    },
    async getServeList(){
      let _self = this, { id, serveTypeIds = [] } = this.currentItem
      let list1 = [], list2 = []
      await buildOneselfServeList({activeId: id, type: 1}).then(res => {
        let {data} = res
        list1 = data.map(i => {
          return {
            serveTypeId: i.serveTypeId,
            id: i.id,
            itemNum: i.itemNum,
            serveImg: i.serveImg,
            serveName: i.serveName,
            serveDetails: i.serveDetails,
            price: i.price,
            discountedPrice: i.discountedPrice,
            writeOffFee: i.writeOffFee,
            isChecked: serveTypeIds.includes(`${i.id}`),
            probability: i.probability || '0'
          }
        }).filter(i => i.isChecked)
      })
      await buildOneselfServeList({activeId: id}).then(res => {
        let {data} = res
        list2 = data.map(i => {
          return {
            serveTypeId: i.serveTypeId,
            id: i.id,
            itemNum: i.itemNum,
            serveImg: i.serveImg,
            serveName: i.serveName,
            serveDetails: i.serveDetails,
            price: i.price,
            discountedPrice:i.discountedPrice,
            writeOffFee: i.writeOffFee,
            isChecked: serveTypeIds.includes(`${i.id}`),
            probability: i.probability || '0'
          }
        }).filter(i => i.isChecked)
      })
      _self.serverList = [...list1, ...list2]
    },
    // 根据商户池获取商户列表
    async queryShopListByPool(){
      let isSuccess = false, _self = this, {shopPool = [], suitShopIds = []} = this.currentItem
      let ids = shopPool.join(',')
      if(!ids) {
        _self.shopList = []
        isSuccess = true
      }else{
        await getShopListByPool(ids).then(res => {
          _self.shopList = res.data.map(item => {
            return {
              id: item.id,
              shopName: item.shopName,
              shopAddress: item.shopAddress,
              isChecked: suitShopIds.includes(`${item.id}`)
            }
          }).filter(i => i.isChecked)
          isSuccess = true
        })
      }
      return isSuccess
    },
    isVehicleNumber(vehicleNumber) {
      // var xreg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
      var xxreg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DABCEFGHJK]$)|([DABCEFGHJK][A-HJ-NP-Z0-9][0-9]{4}$))/;  // 2021年新能源车牌不止有DF

      var creg=/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;

      if(vehicleNumber.length == 7){
        return creg.test(vehicleNumber);
      } else if(vehicleNumber.length == 8){
        return xxreg.test(vehicleNumber);
      } else{
        return false;
      }
    },
    async submit(){
      let _self = this, {id} = this.$route.query
      if(!id) return
      let { startingTime, endTime, acddUsers = [], activityTypeId } = _self.currentItem
      let params = {
        id,
        startingTime,
        endTime
      }
      if(_self.activeFiles.targetedUsers){
        if(!acddUsers.length) return _self.$message.error('请设置定向用户')
        let txtError = ''
        acddUsers.filter(i => i.useStatus == 1).forEach(i => {
          if(!i.name || i.name == '') {
            txtError = '请完善用户名称'
          }
          if(activityTypeId == 2){
            if(!_self.isVehicleNumber(i.licensePlate)){
              txtError = '请填写正确车牌号，字母大写'
            }
            if(!i.orderTimeStart || i.orderTimeStart == '') {
              txtError = '请完善定向开始时间'
            }
            if(!i.payValidDay || i.payValidDay == '') {
              txtError = '请完善定向购买有效期'
            } 
            if(!i.orderPeriodValidity || i.orderPeriodValidity == '') {
              txtError = '请完善定向卡券有效期'
            } 
          }
          if(!i.phone || i.phone == '' || !isPhoneNum(i.phone)) {
            txtError = '请输入正确格式的手机号'
          }
        })
        if(txtError) return _self.$message.error(txtError)
        params.acddUsers = acddUsers || []
      }
      _self.boo.isPrice = true
      editActivityDate(params).then(res => {
        _self.$message.success('操作成功')
        setTimeout(() => {
          _self.$router.go(-1)
        }, 1000)
      }).finally(() => {
        _self.boo.isPrice = false
      })
    },
    addUser(){
      let _self = this, {activityTypeId} = this.currentItem, row = {}
      if(activityTypeId == 6){
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          insureCode: '',
          balance: '',
          phone_error: true,
          name_error: true,
        }
      }else if(activityTypeId == 2){
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          phone_error: true,
          name_error: true,
          orderTimeStart: '',
          payValidDay: 1,
          orderPeriodValidity: 1,
          useStatus: 1,
        }
      }else{
        row = {
          phone: '',
          name: '',
          licensePlate: '',
          phone_error: true,
          name_error: true,
          useStatus: 1,
        }
      }
      _self.currentItem.acddUsers.push(row)
    },
    // 下载用户模板
    exportUserTmp(){
      let {activityTypeId} = this.currentItem, row = {}
      if(activityTypeId == 6){
        exportRedPacketTemplate({}, '用户模板')
      }else if(activityTypeId == 2){
        exportOrientTemplate({}, '用户模板')
      }else if(activityTypeId == 5){
        exportGiveTemplate({}, '用户模板')
      }
    },
    importUser(){
      let dilogVm = this.$refs['importDialog']
      dilogVm.showDialog()
    },
    importSuccess(list){
      let _self = this, {activityTypeId} = this.currentItem
      _self.currentItem.acddUsers = [..._self.currentItem.acddUsers, ...list.map(i => {
        let obj = {
          id: i.id,
          name: i.name,
          phone: i.phone,
          licensePlate: i.licensePlate || '',
        }
        if(activityTypeId == 6){
          obj.insureCode = i.insureCode
          obj.balance = i.balance
        }else if(activityTypeId == 2){
          obj.orderTimeStart = i.orderTimeStart || ''
          obj.payValidDay = i.payValidDay || 1
          obj.orderPeriodValidity = i.orderPeriodValidity || 1
          obj.useStatus =  1
        }else if(activityTypeId == 5){
          obj.useStatus =  1
        }
        return obj
      })]
    },
    removeTargetUser(idx){
      let _self = this
      _self.currentItem.acddUsers.splice(idx, 1)
    },
  }
};
</script>
<style scoped lang="scss">
@import './active-config/action-active.scss';
</style>
<style scoped lang="scss">
.back-content{
  padding: vh(25) vw(20) vh(25) 0;
  .back-icon{
    font-size: vh(36);
    cursor: pointer;
  }
  .back-label{
    margin-left: vw(20);
    font-size: 13px;
    color: #3D3D3D;
  }
}
.action-active-container{
  display: flex;
  flex-direction: column;
  padding-left: vw(20);
  .action-active-main{
    align-items: flex-start;
    .active-config-content{
      width: 90%;
    }
    .active-page-content{
      flex: 1;
      width: 58%;
    }
  }
}
.sums-content{
  align-items: flex-end;
  padding: vh(25) vw(40);
  .sums-item{
    margin-top: vh(10);
    &:first-child{
      margin-top: 0;
    }
    .sums-label{
      font-size: vh(12);
      color: #3E3E3E;
      width: vw(100);
      text-align: right;
      margin-right: vw(40);
      &.desc{
        color: #666666;
      }
    }
    .sums-val{
      font-size: vh(12);
      color: #3E3E3E;
      width: vw(100);
      &.error{
        color: #E2231A;
      }
    }
  }
}
</style>